package com.lemon.smartsafety.ui.fragment.hidden;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.event.hidden.HiddenMainRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.hidden.HiddenMainUIVo;
import com.lemon.smartsafety.entity.hidden.MainHiddenUIItemBase;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.HiddenServices;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.ui.adapter.common.RcvViewType;
import com.lemon.smartsafety.ui.adapter.hidden.main.HiddenMainAdapter;
import com.lemon.smartsafetynew.ui.fragment.base.SwipeRefreshBaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.Convertor;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.safecloud.greendao.HiddenIndexInfo;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.Bind;

/**
 * Created by Cooliean on 16/2/21.
 */
public class HiddenMainFragment extends SwipeRefreshBaseFragment implements RecyclerTClickListener<MainHiddenUIItemBase<HiddenMainUIVo>>, PullToRefreshRecyclerView.OnPullUpToRefreshListener {

    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    HiddenMainAdapter mAdapter;

    private List<MainHiddenUIItemBase<HiddenMainUIVo>> mItems = DataUtil.getHiddenMainUiDatas(false);

    private TextView mCompanyTextView;

    private HiddenIndexInfo mHiddenIndexInfo;


    private int cyclePostion = 1;
    private int zeroPosition = 4;


    private LoggerHelper loggerHelper = new LoggerHelper(HiddenMainFragment.class);


    public static Fragment newInstance(){
        HiddenMainFragment fragment = new HiddenMainFragment();
        return fragment;
    }

    @Override
    protected void initViews() {
        super.initViews();

        mAdapter = new HiddenMainAdapter(mItems, this);

        //mPullToRefreshRecyclerView.setItemAnimator(new SlideInLeftAnimator());
        //mPullToRefreshRecyclerView.getItemAnimator().setAddDuration(Constants.RECYCLE_VIEW_ANIMATOR_DURATION);
        //mPullToRefreshRecyclerView.getItemAnimator().setRemoveDuration(Constants.RECYCLE_VIEW_ANIMATOR_DURATION);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPullToRefreshRecyclerView.beginRefreshing();

    }

    /**
     * 获取网络数据
     */
    private void getNetData() {
        HiddenServices.init().getHiddenMainIndexInfo();
    }


    private void addZeroItem() {
        if (HiddenMainAdapter.HiddenMainUITag.TAG_ZERO == mItems.get(zeroPosition).getTag()) {
            return;
        }
        MainHiddenUIItemBase<HiddenMainUIVo> voZeroItem = new MainHiddenUIItemBase<>();
        voZeroItem.setViewType(RcvViewType.CommonRcvViewType.TYPE_COMMON_ITEM);
        HiddenMainUIVo voZero = new HiddenMainUIVo();
        voZero.setTitle(R.string.hidden_zero_report);
        voZero.setTip(getString(R.string.hidden_zero_tip));

        voZeroItem.setData(voZero);
        voZeroItem.setTag(HiddenMainAdapter.HiddenMainUITag.TAG_ZERO);
        mAdapter.addItem(voZeroItem, zeroPosition);
    }

    /**
     * 获得一个顶部控件
     */
    public View getHeaderView1(int message) {
        return getHeaderView(getString(message));
    }

    /**
     * 获得一个顶部控件
     */
    public View getHeaderView1(String message) {
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.view_login_user_tip_head, (ViewGroup) getActivity().findViewById(android.R.id.content), false);
        header.setBackgroundColor(getResources().getColor(R.color.white));
        mCompanyTextView = (TextView) header;
        mCompanyTextView.setTextColor(getResources().getColor(R.color.colorTextPrimary));
        mCompanyTextView.setText(message);
        return mCompanyTextView;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_no_title;
    }


    @Override
    public void onRefresh() {
        getNetData();
    }

    /**
     * 刷新事件
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HiddenMainRefreshEvent event) {
        if (EventTag.TAG_HIDDEN_DANGER_MAIN_REFRESH.equals(event.getTag())) {
            onRefresh();
        }
    }




    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<HiddenIndexInfo> event) {
        if (EventTag.TAG_HIDDEN_INDEX_INFO.equalsIgnoreCase(event.getTag())) {//获取界面信息
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    mHiddenIndexInfo = event.getObj();
                    handleUI(event.getObj());
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_HIDDEN_DANGER_ZERO_ACTION.equalsIgnoreCase(event.getTag())) {//零隐患上报
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.showHUD();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                if (Constants.Result.SUCCESS == event.getEventResult()) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            getNetData();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }

    }


    /**
     * 刷新界面
     * @param indexInfo
     */
    private void handleUI(HiddenIndexInfo indexInfo) {
        if (indexInfo == null) {
            return;
        }
        if (StringUtils.nullValue(indexInfo.getCompanyName()).length() != 0) {
            if (mPullToRefreshRecyclerView.getHeaderViewCount() <= 1) {
                mPullToRefreshRecyclerView.addHeaderView(getHeaderView1(indexInfo.getCompanyName()));
            } else {
                mCompanyTextView.setText(indexInfo.getCompanyName());
            }
        }
        if (StringUtils.nullValue(indexInfo.getCurrentStartDate()).length() != 0 && StringUtils.nullValue(indexInfo.getCurrentEndDate()).length() != 0) {
            String cycleString = indexInfo.getCurrentStartDate() + "~" + indexInfo.getCurrentEndDate() + "(" + indexInfo.getCycleType() + ")";
            DataUtil.getHiddenMainUIItemByTag(mItems, HiddenMainAdapter.HiddenMainUITag.TAG_CYCLE).getData().setTip(cycleString);
            mAdapter.notifyItemChanged(cyclePostion);
        }
        DataUtil.getHiddenMainUIItemByTag(mItems, HiddenMainAdapter.HiddenMainUITag.TAG_REPORT_COUNT).getData().setTip(StringUtils.nullValue(indexInfo.getDangerCount(), "0"));
        mAdapter.notifyItemChanged(cyclePostion + 1);
        if (Convertor.toInt(StringUtils.nullValue(indexInfo.getDangerCount(), "0")) <= 0) {
            addZeroItem();
        }
    }

    @Override
    public void onItemClick(MainHiddenUIItemBase<HiddenMainUIVo> data, int position) {
        if (HiddenMainAdapter.HiddenMainUITag.TAG_ZERO == data.getTag()) {
            new MaterialDialog.Builder(getActivity()).title(R.string.tip_str_title)
                    .content(R.string.hidden_zero_report_confirm)
                    .positiveText(R.string.sure_str)
                    .negativeText(R.string.cancel_str)
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (which == DialogAction.POSITIVE) {
                                String companyCode = StringUtils.nullValue(mHiddenIndexInfo.getCompanyCode(), "");
                                if (mHiddenIndexInfo != null && companyCode.length() != 0) {
                                    HiddenServices.init().sendZeroDanger(companyCode);
                                }else{
                                    mHUDUtil.showErrorTip(getString(R.string.handle_success));
                                }
                            }
                        }
                    }).show();
        } else if (HiddenMainAdapter.HiddenMainUITag.TAG_UPLOAD_REPORT == data.getTag()) {
            UIHelper.showHiddenPropActivity(getActivity());
        } else if (HiddenMainAdapter.HiddenMainUITag.TAG_MODIFY_HIDDEN == data.getTag()) {
            UIHelper.showHiddenListActivity(getActivity());
        }
    }
}
